package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
//@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        log.info("请求路径：{}", path);

        if (path.endsWith("/login")) {
            log.info("登录请求 , 直接放行");
            return true;
        }
        String token = request.getHeader("Token");
        log.info("token的值为：{}",token);
        if (StringUtils.hasText(token)) {
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("用户的信息为：{}", claims);
                return true;
            } catch (Exception e) {
                log.error("解析token失败", e);
            }
        }
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        return false;
    }
}
